import { useResize } from '@shared/lib/hooks/useResize'
import { Tooltip } from '@shared/ui/Tooltip'
import classNames from 'classnames'
import { Fragment, ReactNode } from 'react'
import { NavLink } from 'react-router-dom'
import { MenuSkeleton } from './MenuSkeleton/MenuSkeleton'
import { MenuTitle } from './MenuTitle/MenuTitle'
import styles from './MenuSection.module.scss'

export interface MenuItem {
  count?: number
  icon?: string
  title: string
  to: string
}

interface MenuSectionProps {
  className?: string
  isLoading?: boolean
  isNav?: boolean
  menuList: MenuItem[]
  onClick?: (item: string) => void
  renderButton?: () => ReactNode
  title?: string
}

interface ListWrapperProps {
  children: ReactNode
  isNav?: boolean
}

const ListWrapper = ({ children, isNav }: ListWrapperProps) => {
  if (isNav) {
    return <nav>{children}</nav>
  }
  return <>{children}</>
}

export const MenuSection = ({
  className,
  isLoading,
  isNav,
  menuList,
  onClick,
  renderButton,
  title,
}: MenuSectionProps) => {
  const { isScreenMd } = useResize()
  const menuItemType = isNav ? styles.nav : styles.default
  const menuItemTypeStyles = classNames(styles['menu-item'], menuItemType)

  const getMenuItemClass = ({ isActive }: { isActive: boolean }): string =>
    classNames(menuItemTypeStyles, {
      [styles.active]: isActive,
    })

  if (isLoading) {
    return <MenuSkeleton title={title} />
  }

  return (
    <section className={classNames(styles.section, className)}>
      {title && <MenuTitle renderButton={renderButton} title={title} />}
      <ListWrapper isNav={isNav}>
        {menuList.map(({ count, icon, title, to }) => (
          <Fragment key={title}>
            <NavLink
              className={getMenuItemClass}
              data-tooltip-content={title}
              data-tooltip-id={title}
              onClick={() => onClick?.(title)}
              to={to}
            >
              <div className={styles['icon-wrapper']}>
                <span className={classNames('material-symbols-rounded', styles.icon)}>{icon}</span>
              </div>
              {isScreenMd && <span className={styles.label}>{title}</span>}
              {count && <span className={styles.count}>{count}</span>}
            </NavLink>
            {!isScreenMd && <Tooltip id={title} place='right' />}
          </Fragment>
        ))}
      </ListWrapper>
    </section>
  )
}

MenuSection.displayName = 'MenuSection'
